package cn.com.ry.framework.mongodb.sync.handler;

import cn.com.ry.framework.mongodb.sync.service.SynService;
import cn.com.ry.framework.mongodb.sync.util.Consumer;
import cn.com.ry.framework.mongodb.sync.util.Producer;
import cn.com.ry.framework.mongodb.sync.util.SynLogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;

@Component
@Order(2)
public class RunSynHandler {
    private static final Logger logger = LoggerFactory.getLogger(RunSynHandler.class);
    @Autowired
    Consumer consumer;
    @Autowired
    Producer producer;
    @Autowired
    private SynLogUtil synLogUtil;
    @Autowired
    private SynService synService;

    //线程数
    @Value("${syn.consuer.threadnum:20}")
    private int THREAD_NUM = 20;
    @Value("${syn.point.flag:false}")
    private boolean pointFlag;
    //日志地址
    @Value("${syn.log.path:D:/syn-log.properties}")
    private String path;

    @Value("${create.index.flag:false}")
    private boolean createIndex;

    @Autowired
    ExecutorService executorService;

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    MongoTemplate mongoTemplate;

    @PostConstruct
    public void run() {
        if (createIndex) {
            synService.createIndex();
        } else {
            //创建mongodb没有的表
            synService.createOtherTable();
            //加载日志文件
            if (pointFlag) {
                logger.info("开启断点续传");
                logger.info("[开始]加载断点续传文件" + path);
                try {
                    synLogUtil.setProperties(path);
                    logger.info("[成功]加载断点续传文件" + path);
                } catch (Exception e) {
                    logger.info("[失败]加载断点续传文件" + path);
                    return;
                }
            }

            //初始化线程
            BlockingQueue queue = new ArrayBlockingQueue(1024);
            producer.setProducer(queue);
            consumer.setConsumer(queue);
            //生产者线程池
            executorService.submit(producer);
            //消费者线程池
            for (int i = 0; i < THREAD_NUM; i++) {
                executorService.submit(consumer);
            }

        }
    }

}
